local jijian = fk.CreateSkill{
  name = "investiture__jijian",
  tags = {"Round"},
}

Fk:loadTranslationTable{
  ["investiture__jijian"] = "激谏",
  [":investiture__jijian"] = "轮次技，当你于回合外需要使用【无懈可击】时，你可视为使用之，然后若当前回合角色为本轮伤害唯一最多，你重置此技能；"
  .."否则，你可与其各对对方造成1点伤害，若其仍不为本轮造成伤害唯一最多，你将其手牌弃置至与场上手牌数最小的角色相同。",
  ["#investiture__jijian-damage"] = "激谏：可以与 %src 各对对方造成1点伤害",

  ["#investiture__jijian-discard"] = "激谏：请弃置 %dest 的%arg张手牌",

  ["$investiture__jijian1"] = "为人臣者，不得不以死争。",
  ["$investiture__jijian2"] = "主过不谏非忠也，畏死不言非勇也。",
}

--- damage counter
---@param room Room
---@return table<Player, number>
local damage_counter = function (room)
  local map = {}
  for _, p in ipairs(room.alive_players) do
    map[p] = 0
  end

  local end_event = room.logic:getCurrentEvent():findParent(GameEvent.Round, true)
  if not end_event then return map end
  local events = room.logic.event_recorder[GameEvent.Damage] or Util.DummyTable ---@type GameEvent.Damage[]
  for i = #events, 1, -1 do
    local e = events[i]
    if e.id <= end_event.id then break end
    if e.data.from then
      local n = e.data.damage
      if e.data.isVirtualDMG then n = 0 end
      map[e.data.from] = map[e.data.from] + n
    end
  end

  return map
end

--- hand card num difference counter
---@param target ServerPlayer
---@return integer
local differ_counter = function (target)
  local room = target.room
  local min = 999
  for _, p in ipairs(room.alive_players) do
    if p:getHandcardNum() < min then
      min = p:getHandcardNum()
    end
  end

  return target:getHandcardNum() - min
end

--- current caused damage most?
---@param player ServerPlayer
---@return boolean
local damage_max = function (player)
  local room = player.room
  local map = damage_counter(room)
  return table.every(room.alive_players, function(p) return p == room.current or map[p] < map[room.current] end)
end

--- second invoke
--- @param player ServerPlayer
--- @param target ServerPlayer
local second_invoke = function (player, target)
  local room = player.room
  local ivk = room:askToSkillInvoke(player, {
    skill_name = jijian.name,
    prompt = "#investiture__jijian-damage:" .. target.id,
  })
  if not ivk then return end

  room:damage{
    damage = 1,
    to = target,
    skillName = jijian.name,
    from = player,
  }
  if not (target.dead or player.dead) then
    room:damage{
      damage = 1,
      to = player,
      skillName = jijian.name,
      from = target,
    }
  end

  if player.dead then return end

  local map = damage_counter(room)
  if not table.every(room.alive_players, function(p) return p == target or map[p] < map[target] end) then
    local dif = differ_counter(target)
    if dif <= 0 then return end

    local cards = room:askToChooseCards(player, {
      target = target,
      flag = "h",
      max = dif,
      min = dif,
      skill_name = jijian.name,
      prompt = "#investiture__jijian-discard::" .. target.id .. ":" .. dif,
    })
    room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonDiscard, jijian.name, nil, true, player)
  end
end

--- main effect
jijian:addEffect("viewas", {
  anim_type = "defensive",
  pattern = "nullification",
  card_filter = Util.FalseFunc,
  view_as = function (self, player, cards)
    local card = Fk:cloneCard("nullification")
    card.skillName = jijian.name
    return card
  end,
  enabled_at_response = function (self, player, response)
    return not response and player ~= Fk:currentRoom().current
    and player:usedSkillTimes(jijian.name, Player.HistoryRound) == 0
  end,
  after_use = function (self, player, use)
    if damage_max(player) then
      for h = Player.HistoryPhase, Player.HistoryGame do
        player:setSkillUseHistory(jijian.name, 0, h)
      end
    else
      local current = player.room.current
      if player.dead or current.dead then return end
      second_invoke(player, current)
    end
  end
})

return jijian